<template>
    <view class="wrapper">
        <BSseMessage @receiveOrder="handleReceiveOrder"/>
        <BMap ref="mapRef"/>
    </view>
</template>

<script setup>
	import BSseMessage from '../component/BSseMessage.vue';
	import BMap from '../component/BMap.vue';
	import { computed, onMounted, onBeforeUnmount, provide, ref, watch } from 'vue';
	import { ApiGetCityList } from "../api/city.js";
	import { useStore } from 'vuex';
	const mapRef = ref(null);
	const $store = useStore();
	let city = computed(()=> $store.state.city);
	let orderId = null;
	
	onMounted(() => {
		// 监听city的变化
		setLocation();  // 默认北京
		watch(city, setLocation);
		getLocation();
	});

	const handleReceiveOrder = (arg) =>{
		orderId = arg.orderId;
		uni.redirectTo({url:`/pages/orderDetail?orderId=${orderId}`});
	}
	
	/**
	 * @Description: 默认定位到当前城市
	 * @return {*}
	 */
	const getLocation = async () => {
	    const {error, result}= await ApiGetCityList();
		uni.getLocation({
			type: 'gcj02',
			geocode: true,
			success (res) {
			  // console.log(JSON.stringify(res))
			  const {address,longitude,latitude, accuracy} = res;
			  $store.commit('setCity',{
				adcode : result.find(i => i.citycode === address.cityCode).adcode,
				cityCode: address.cityCode,
				name: address.city,
				center: `${longitude},${latitude}`,
				accuracy: `${accuracy}`,
				locationRes: true
			  });
			},
			fail(err) {
			    console.error('获取位置信息失败:', err);
				setLocation();  // 默认北京
			}
		});
	}

    function setLocation (){
		// console.log(city.value)
		if (!mapRef.value) {
		    return;
		}
		const location = {
			"center" : city.value.center.split(','),
			"accuracy": city.value.accuracy,
			"locationRes" : city.value.locationRes
		}
		mapRef.value.setLocation(location);
		setTimeout(()=>mapRef.value.clearDriving(), 500);
	}	

</script>

<style lang="scss" scoped>
	.wrapper {
	    width: 100%;
	    height: 100vh;
	}
</style>
